package per.hx.bs.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import per.hx.bs.config.AuthorizeException;
import per.hx.bs.service.RedisService;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HuXing
 * @date 2018/5/13  20:00
 */
@Aspect
@Component
public class AuthorizeAspect {

    private final static Logger logger = LoggerFactory.getLogger(AuthorizeAspect.class);

    private final
    RedisService redisService;

    @Autowired
    public AuthorizeAspect(RedisService redisService) {
        this.redisService = redisService;
    }


    /**
     * 切入点所有的 authorize 包下的文件
     */
    @Pointcut(value = "execution(* per.hx.bs.authorize.*.*(..))")
    private void authorize() {
    }

    @ResponseBody
    @Around("authorize()")
    public Object isAccessMethod(ProceedingJoinPoint pjp) throws Throwable {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String loginFlag = request.getHeader("loginFlag");
        logger.info(loginFlag);
        logger.info((String) redisService.get(loginFlag));
        if (redisService.hasKey(loginFlag)) {
            return pjp.proceed();
        } else {
            throw new AuthorizeException("登录标识符无效");
        }
    }

}
